package com.hw.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hw.constants.ConstantCode;
import com.hw.controller.ChatingHandler;
import com.hw.dao.CategoriesDao;
import com.hw.dao.DevicesDao;
import com.hw.event.DeviceEvent;
import com.hw.exceptions.MyBaseException;
import com.hw.pojo.Categories;
import com.hw.pojo.Devices;
import com.hw.service.DevicesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.WebSocketSession;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: DevicesServiceImpl
 * @Description:
 * @Author: vie0134
 * @Date: 2020-12-15 17:07
 * @Version: 1.0
 **/
@Service
public class DevicesServiceImpl implements DevicesService {

    @Autowired
    private DevicesDao devicesDao;
    @Autowired
    private CategoriesDao categoriesDao;
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public PageInfo<Devices> findAllDevices(int pageNum, int pageSize, String address, String status, Integer areaid, Integer categoryid) {
        PageHelper.startPage(pageNum, pageSize);

        try {
            List<Devices> allDevices = devicesDao.findAllDevices(address, status, areaid, categoryid);
//            allDevices.forEach(devices -> {devices.commandsjson(null);});
            allDevices.forEach(device -> {
                WebSocketSession session = ChatingHandler.getClient(device.getDevicesuuid());
                if (session != null && session.isOpen()) {
                    device.setStatus("1");//设置在线
                }
            });
            return new PageInfo<>(allDevices);
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new MyBaseException("查询异常", ConstantCode.ERROR);
    }

    @Override
    public void addDevices(Devices devices) {
        if (devices == null) {
            throw new MyBaseException("数据不为空", ConstantCode.DATA_NOT_TRANSFER);
        }
        try {
            devicesDao.addDevices(devices);
            return;
        } catch (Exception e) {
            e.printStackTrace();
            throw new MyBaseException("添加失败", ConstantCode.ERROR);
        }
    }

    @Override
    public void updateDevices(Devices devices) {
        if (devices == null || StringUtils.isEmpty(devices)) {
            throw new MyBaseException("数据不为空", ConstantCode.DATA_NOT_TRANSFER);
        }
        try {
            devicesDao.updateDevices(devices);
            return;
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new MyBaseException("修改失败", ConstantCode.ERROR);
    }

    @Override
    public void deleteDevicesById(Integer id) {
        if (id == null) {
            throw new MyBaseException("没有传递id", ConstantCode.DATA_NOT_TRANSFER);
        }
        try {
            devicesDao.deleteDevicesById(id);
            return;
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new MyBaseException("删除失败", ConstantCode.ERROR);
    }

    @Override
    public void deleteDevicesByIds(List<String> ids) {
        if (ids == null || ids.size() == 0) {
            throw new MyBaseException("没有传递id", ConstantCode.DATA_NOT_TRANSFER);
        }
        try {
            devicesDao.deleteDevicesByIds(ids);
            return;
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new MyBaseException("删除失败", ConstantCode.ERROR);
    }

    @Override
    public Devices findDevicesById(Integer id) {
        if (id == null || id == 0) {
            throw new MyBaseException("数据为空", ConstantCode.DATA_NOT_TRANSFER);
        }
        try {
            Devices devices = devicesDao.findDevicesById(id);
            if (devices == null) {
                throw new MyBaseException("没有数据", ConstantCode.NULL_DATA);
            }
            WebSocketSession session = ChatingHandler.getClient(devices.getDevicesuuid());
            if (session != null && session.isOpen()) {
                devices.setStatus("1");
            }
            return devices;
        } catch (Exception e) {
            e.printStackTrace();
            throw new MyBaseException("查询失败", ConstantCode.ERROR);
        }
    }

    @Override
    public Devices findDevicesByUUID(String uuid) {
        return null;
    }

    @Override
    public void sendControl(String uuid, String command) {
        if (StringUtils.isEmpty(uuid) || StringUtils.isEmpty(command)) {
            throw new MyBaseException("获取的数据不完整", ConstantCode.DATA_NOT_TRANSFER);
        }
        try {
            Integer categoryIdByUUID = devicesDao.getCategoryIdByUUID(uuid);
            if (categoryIdByUUID == null) {
                throw new MyBaseException("设备分类不存在", ConstantCode.NULL_DATA);
            }
            Categories categories = categoriesDao.findCategoriesById(categoryIdByUUID);
            if (categories == null) {
                throw new MyBaseException("设备分类不存在", ConstantCode.NULL_DATA);
            }

            String commandsjson = categories.getCommandsjson();
            Map map = objectMapper.readValue(commandsjson, Map.class);
            int result = ChatingHandler.sendControl(uuid, (String) map.get(command));
            if (result > 0) {
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new MyBaseException("对方不在线,发送失败", ConstantCode.DEVICE_NOT_ONLINE);
    }

    @Override
    public void onEvent(DeviceEvent deviceEvent) {
        switch (deviceEvent.getType()) {
            case OPEN:
                devicesDao.updateConnectionTime(deviceEvent.getUuid(), new Date());
                break;
            case CLOSE:
                devicesDao.updateOffLine(deviceEvent.getUuid(), "0");
                break;
        }
    }
}
